import React, { useState, useEffect } from "react";
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Space, Button, DatePicker, Modal, Row, Col, InputNumber, message, Tag, } from "antd";
import { SearchOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack'
import { apiStockPurchaseAdd, apiStockPurchaseDetailsAdd, apiStockPurchaseDetailsDelet, apiStockPurchaseDetailsEdit } from "@/request/procurement"
import { apiGetGoodsList, apiGetGoodsDetail } from '@/request/marketingTool'
import '../style/index.scss'
import _ from "lodash";

const { Option } = Select
const addFormRef = React.createRef()
const ProcureAdd = (props) => {
    const [Purchase, setPurchase] = useState(null)
    const [isSave, onSave] = useState(false);
    const [isModalVisible, addVisible] = useState(false);
    const [library, setLibraryName] = useState(null);
    const [supplier, setSupplierName] = useState(null);
    const [libraryId, setLibraryId] = useState(null);
    const [supplierId, setSupplierId] = useState(null);
    const [dataSource, setdataSource] = useState([]);
    const [goodsList, setGoodsList] = useState([]);
    const [productSku, setProductSku] = useState([]);
    const [currentSku, setCurrentSkuSku] = useState([]);
    const [materialId, setMaterialId] = useState([]);
    const [submit, setSubmit] = useState(true)
    const [addgoods, setAddgoods] = useState(true);
    const [modalTitle, setModalTitle] = useState('添加')
    const [editID, setEditID] = useState(null)
    const [btnStatus, setBtnStatus] = useState(true)
    const [isOutsource, setIsOutsource] = useState(true)
    const columns = [
        {
            title: "采购单号",
            dataIndex: "code",
            key: "code",
        },
        {
            title: "商品名称",
            dataIndex: "goodsName",
            key: "goodsName",
        },
        {
            title: '物料名称',
            dataIndex: 'materialName',
            key: 'materialName'
        },
        {
            title: "物料编码",
            dataIndex: "goodsSkuNo",
            key: "goodsSkuNo",
        },
        {
            title: "规格名",
            dataIndex: "goodsSkuName",
            key: "goodsSkuName",
        },
        // {
        //     title:"skuID",
        //     dataIndex:"goodsSkuId",
        //     key:"goodsSkuId",
        // },
        {
            title: "含税单价",
            dataIndex: "taxPrice",
            key: "taxPrice",
            render: (text) => {
                return <React.$Price price={Number(text)} />
            }
        },
        {
            title: "含税总价",
            dataIndex: "taxNumPrice",
            key: "taxNumPrice",
            render: (text) => {
                return <React.$Price price={Number(text)} />
            }
        },
        {
            title: "应收数量",
            dataIndex: "shouldInNum",
            key: "shouldInNum",
        },
        {
            title: "操作",
            key: "todo",
            render: (text, render, index) => {
                return isOutsource ? null : <div>
                    {btnStatus ? <TheButton haspermi={['procurement:details:edit']} onClick={() => editGoods(true, render)}>编辑</TheButton> : []}
                    <TheButton haspermi={['procurement:details:delet']}
                        onClick={() => detailsDel(render.id, index)}>删除</TheButton>
                </div>
            }
        },
    ]
    useEffect(() => {
        React.$post('/admin/stockLibraryManage/list').then(
            (res) => {
                if (res.code === 0 && res.data) {
                    let len = res.data.length
                    let option = []
                    for (let i = 0; i < len; i++) {
                        option.push(
                            {
                                label: res.data[i].name,
                                value: res.data[i].id
                            }
                        )
                    }
                    setLibraryName(option)
                }
            }
        )
        React.$post('/admin/stockSupplierManage/list').then(
            (res) => {
                if (res.code === 0 && res.data) {
                    let len = res.data.length
                    let option = []
                    for (let i = 0; i < len; i++) {
                        option.push(
                            {
                                label: res.data[i].supplierName,
                                value: res.data[i].id
                            }
                        )
                    }
                    setSupplierName(option)
                }
            }
        )
    }, [])
    const libraryChange = (e) => {
        setLibraryId(e)
        apiGetGoodsList({ libraryId: e, type: 1 }).then(
            (res) => {
                if (res.code === 0 && res.data) {
                    setGoodsList(res.data)
                }
            }
        )
    }
    const supplierChange = (e) => {
        setSupplierId(e)
    }
    let reset = () => {
        setProductSku([])
        addFormRef.current.setFieldsValue({
            goodsId: '',
            shouldInNum: '',
            taxPrice: "",
            taxNumPrice: ""
        })
    }
    let detailsDel = (id, index) => {
        apiStockPurchaseDetailsDelet({ id }).then(
            (res) => {
                if (res.code === 0) {
                    message.info("删除成功")
                    dataSource.splice(index, 1)
                    setdataSource([...dataSource])
                    // console.log(dataSource);
                }
            }
        )
    }
    let createProcurement = () => {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '创建采购订单后将不可修改，确定创建采购订单吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                if (libraryId === null) {
                    message.error("采购仓库不能为空！")
                    return
                }
                if (supplierId === null) {
                    message.error("供应商不能为空！")
                    return
                }
                let params = {
                    libraryId: libraryId,
                    supplierId: supplierId,
                }
                await apiStockPurchaseAdd({ ...params }).then(
                    (res) => {
                        if (res.code === 0) {
                            if (res.data.isOutsource) {
                                setIsOutsource(false)
                            }
                            setPurchase(res.data)
                            onSave(true)
                        }
                    }
                )
            }
        });
    }
    let selectFilter = (input, option) => {
        const materialIds = option.option.materialIds.toLowerCase().split(',')
        const result = option.children.toLowerCase().includes(input.toLowerCase()) || materialIds.includes(input.toLowerCase())
        return result
    }
    let addGoods = (e) => {
        addVisible(e)
        setModalTitle('添加')
        if (e === false) {
            reset()
        }
    }
    let editGoods = async (e, data) => {
        await addVisible(e)
        setModalTitle('修改')
        // console.log(data)
        if (data) {
            setEditID(data.id)
            apiGetGoodsDetail({ goodsId: data.goodsId, libraryId }).then(
                (res) => {
                    if (res.code === 0) {
                        setProductSku(res.data)
                        let result = res.data.skuInfo.filter(item => item.materialId === data.goodsSkuNo)
                        setCurrentSkuSku(result.length > 0 ? result[0] : res.data.skuInfo[0])
                    }
                }
            )
            addFormRef.current.setFieldsValue({
                goodsId: data.goodsId,
                shouldInNum: data.shouldInNum,
                taxPrice: data.taxPrice / 100,
                taxNumPrice: data.taxNumPrice / 100
            })
        }
        if (e === false) {
            reset()
        }
    }
    let goodsChange = (e, row) => {
        GetGoodsDetail(e)
    }
    let triggerSkuTag = (value) => {
        setCurrentSkuSku(value)
    }
    let onFinishAdd = (value) => {
        let skuName = currentSku.skuAttribute.map(item =>
            item.value
        ).join(",")
        console.log(value);
        let params = {
            purchaseNoteId: Purchase.id,
            goodsName: productSku.goodsInfo.goodsName,
            goodsSkuNo: currentSku.goodsSkuNo,
            goodsSkuName: skuName,
            goodsSkuId: currentSku.SKUId,
            shouldInNum: value.shouldInNum,
            taxPrice: (value.taxPrice * 100).toFixed(0),
            taxNumPrice: (value.taxNumPrice * 100).toFixed(0),
            code: Purchase.code,
        }
        console.log(params);
        if (modalTitle == '添加') {
            apiStockPurchaseDetailsAdd({ ...params }).then(
                (res) => {
                    if (res.code === 0 && res.data) {
                        setdataSource([...dataSource, res.data])
                        // console.log(dataSource);
                        addGoods(false)
                    }
                }
            )
        } else {
            params.id = editID;
            params.goodsId = value.goodsId
            apiStockPurchaseDetailsEdit({ ...params }).then(
                (res) => {
                    if (res.code === 0 && res.data) {
                        dataSource.map(item => {
                            if (item.id == editID) {
                                Object.assign(item, params)
                            }
                            return item
                        })
                        setdataSource([])
                        setdataSource([...dataSource])
                        editGoods(false)
                    }
                }
            )
        }
    }
    let execute = (e) => {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "是否确定操作？",
            onOk: async () => {
                let res = await React.$post("/admin/stockPurchaseNote/edit", {
                    id: Purchase.id,
                    status: e
                })
                if (res.code === 0) {
                    setAddgoods(e ? false : true)
                    // setSubmit(false)
                    setBtnStatus(e ? false : true)
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                }
            }
        })

    }
    let GetGoodsDetail = (goodsId, skuId) => {
        apiGetGoodsDetail({ goodsId, libraryId }).then(
            (res) => {
                if (res.code === 0) {
                    if (materialId) {
                        setProductSku(res.data)
                        let result = res.data.skuInfo.filter(item => item.materialId === materialId)
                        setCurrentSkuSku(result.length > 0 ? result[0] : res.data.skuInfo[0])
                    } else {
                        setProductSku(res.data)
                        setCurrentSkuSku(res.data.skuInfo[0])
                    }
                }
            }
        )
    }
    const onBlur = (materialId) => {
        setMaterialId(materialId)
    }
    const onValuesChange = (obj, values) => {
        let { shouldInNum, taxPrice, taxNumPrice } = values
        Object.keys(obj).forEach(item => {
            if (item == 'shouldInNum' || item == 'taxPrice') {
                try {
                    taxNumPrice = shouldInNum * taxPrice
                    addFormRef.current.setFieldsValue({
                        taxNumPrice
                    })
                } catch (error) {
                    console.warn('计算异常');
                }
            }
        })

        // taxNumPrice 总价
        // taxPrice 单价
        // shouldInNum 入库数
    }
    return (
        <div className="p-layout-box">
            <GoBack history={props.history} title="创建采购订单" />
            <Form
                labelCol={{
                    span: 6,
                }}
                wrapperCol={{
                    span: 18,
                }}
                style={{ marginBottom: 12, marginTop: 12 }}>
                <Row>
                    {/* <Col span={8}>
                        <Form.Item name={"storeServiceName"} label="采购日期" >
                            <Input placeholder={"出库时间"}  />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name={"storeServiceName1"} label="采购类型" >
                            <Input placeholder={"出库类型"} />
                        </Form.Item>
                    </Col> */}
                    <Col span={8}>
                        <Form.Item name={"libraryId"} label="采购仓库"
                            rules={[{ required: true }]}>
                            <Select placeholder={"采购仓库"} disabled={isSave} options={library}
                                optionFilterProp="children"
                                showSearch
                                filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                onChange={libraryChange} />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name={"supplierId"} label="供应商"
                            rules={[{ required: true }]}>
                            <Select placeholder={"供应商"}
                                showSearch
                                options={supplier}
                                onChange={supplierChange}
                                disabled={isSave}
                                filterOption={(input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                }
                            >
                                {/* <option value={1}>123</option>
                                <option value={2}>234</option>
                                <option value={3}>345</option>
                                <option value={4}>456</option> */}
                            </Select>
                        </Form.Item>
                    </Col>
                    {/* <Col span={8}>
                        <Form.Item name={"storeServiceName4"} label="登记人">
                            <Input placeholder={"领取人"} />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name={"storeServiceName5"} label="验收人">
                            <Input placeholder={"领取部门"} />
                        </Form.Item>
                    </Col> */}
                </Row>
            </Form>
            <div style={{ marginBottom: 12 }}>
                {
                    !isSave ?
                        <TheButton haspermi={['procurement:list:add']} onClick={createProcurement} size="middle"
                            type="primary">创建采购订单</TheButton>
                        :
                        <div>
                            {/* <TheButton style={{ marginRight: 8 }} haspermi={['procurement:list:upload']} size="middle" type="default">导入</TheButton>
                            <TheButton style={{ marginRight: 8 }} haspermi={['procurement:list:downLoad']} size="middle" type="default">导出</TheButton> */}
                            {addgoods && <TheButton onClick={() => addGoods(true)} haspermi={['procurement:goods:add']}
                                size="middle" type="primary">添加商品</TheButton>}
                        </div>
                }
            </div>
            <TheTable
                scroll={{ x: "max-content", y: '63vh' }}
                columns={columns}
                dataSource={dataSource}
            />
            {/* <ThePagination
                pageNo={1}
                pageSize={10}
                total={0}
            // pageChange={this.pageChange}
            /> */}
            <div style={{ textAlign: 'center', marginTop: 12 }}>
                {
                    submit ? (btnStatus ?
                        <TheButton type="primary" haspermi={['procurement:list:backout']} size='middle'
                            onClick={() => execute(1)}>提交</TheButton> :
                        <TheButton type="default" haspermi={['procurement:list:execute']} size='middle'
                            onClick={() => execute(0)}>撤销</TheButton>) : []
                }
            </div>

            <Modal title={modalTitle + "采购商品"} visible={isModalVisible} width="40%"
                onCancel={() => addGoods(false)}
                footer={null}
            >
                <Form
                    labelCol={{
                        span: 4,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    onValuesChange={onValuesChange}
                    ref={addFormRef}
                    onFinish={(values) => onFinishAdd(values)}
                >
                    <Row>

                        <Col span={24}>
                            <Form.Item

                                label="选择商品"
                                name="goodsId"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择商品!',
                                    },
                                ]}
                            >
                                <Select

                                    showSearch
                                    optionFilterProp="children"
                                    filterOption={(input, option) => selectFilter(input, option)}
                                    style={{
                                        width: '100%',
                                    }}
                                    onSearch={(e) => onBlur(e)}
                                    onSelect={(e, obj) => goodsChange(e, obj)}
                                    placeholder="请选择商品"
                                >
                                    {

                                        goodsList.map(item => <Option option={item} key={item.goodsId}
                                            value={item.goodsId}>{item.goodsName}</Option>)
                                    }
                                </Select>

                            </Form.Item>
                        </Col>

                        <Col>
                            {
                                productSku.hasOwnProperty('goodsInfo') ?
                                    <Form.Item
                                        wrapperCol={{
                                            offset: 4,
                                            span: 16,
                                        }}
                                    >
                                        <div className='goodsDesc'>
                                            <div className='info'>
                                                <img
                                                    src={currentSku.imageFile ? currentSku.imageFile.split(',')[0] : ''}
                                                    alt="商品图片" className='goodsImg' />
                                                <div className="goodsInfo">
                                                    <div className='name'>{productSku.goodsInfo.goodsName}</div>
                                                    <div className="stock">
                                                        物料名称：{currentSku.materialName}
                                                    </div>
                                                    <div className='stock'>
                                                        物料ID：{currentSku.materialId}
                                                    </div>
                                                    <div className='stock'>
                                                        可售库存：{currentSku.stock}
                                                    </div>
                                                    <div className='stock'>
                                                        待出库存：{currentSku.waiteOutCount}
                                                    </div>
                                                    <div className='stock'>
                                                        实际库存：{currentSku.realStock}
                                                    </div>
                                                </div>
                                            </div>
                                            <div className='goodsSku'>
                                                {
                                                    productSku.skuInfo.map(item =>
                                                        <Tag className='tag' key={item.SKUId}
                                                            color={item.SKUId === currentSku.SKUId ? "cyan" : ''}
                                                            onClick={() => triggerSkuTag(item)}>
                                                            {item.skuAttribute.map(item2 => item2.value).join(',')}
                                                        </Tag>
                                                    )
                                                }

                                            </div>
                                        </div>
                                    </Form.Item> : null
                            }
                        </Col>

                        {/* <Col span={24}>
                        <Form.Item
                            label="入库类型"
                            name="dataType"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入!',
                                },
                            ]}
                        >
                            <Select>
                                {
                                    options.map(item => {
                                        return <Option value={item.value}>{item.label}</Option>
                                    })
                                }

                            </Select>
                        </Form.Item>
                    </Col> */}
                        <Col span={24}>
                            <Form.Item
                                label="入库数"
                                name="shouldInNum"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入!',
                                    },
                                ]}
                            >
                                <InputNumber style={{}} precision={0} min={0} />
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                label="含税单价"
                                name="taxPrice"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入!',
                                    },
                                ]}
                            >
                                <InputNumber style={{}} precision={2} min={0} />
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                label="含税总价"
                                name="taxNumPrice"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入!',
                                    },
                                ]}
                            >
                                <InputNumber style={{}} precision={2} min={0} />
                            </Form.Item>
                        </Col>

                        <Col>
                            <Form.Item wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}>
                                <Space size="small" style={{ marginLeft: 10 }}>

                                    <Button type="default" onClick={() => reset()}>
                                        重置
                                    </Button>
                                    <Button type="primary" htmlType="submit">
                                        确定
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </div>
    );
}

export default ProcureAdd
